//
//  SelectRoomViewController.swift
//  ElectricBalance
//
//  Created by David on 2017/1/18.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit
protocol RoomSelectDelegate {
    func didFinishSelectRoom(vc: SelectRoomViewController)
}
class SelectRoomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var delegate: RoomSelectDelegate?
    
    var buildTableView: UITableView!
    var floorTableView: UITableView!
    var roomTableView: UITableView!
    
    var buildList: [Any]?
    var floorList: [Any]?
    var roomList: [Any]?
    
    var selectedBuildID:String?
    var selectedFloorID:String?
    var selectedRoomID:String?
    
    var dormName:String?
    var roomName:String?
    
    convenience init(buildingList: [Any]?){
        self.init()
        buildList = buildingList
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "选择宿舍"
        
        buildTableView = UITableView(frame: view.frame)
        buildTableView.tag = 1
        buildTableView.delegate = self
        buildTableView.dataSource = self
        view.addSubview(buildTableView)
        
        floorTableView = UITableView(frame: CGRect(x: view.frame.width/3, y: 64, width: view.frame.width*2/3, height: view.frame.height))
        floorTableView.tag = 2
        floorTableView.delegate = self
        floorTableView.dataSource = self
        view.addSubview(floorTableView)
        floorTableView.alpha = 0
        
        roomTableView = UITableView(frame: CGRect(x: view.frame.width*2/3, y: 64, width: view.frame.width/3, height: view.frame.height))
        roomTableView.tag = 3
        roomTableView.delegate = self
        roomTableView.dataSource = self
        view.addSubview(roomTableView)
        roomTableView.alpha = 0
        
        if buildList == nil{
            getList(build: nil, floor: nil)
        }
        
//        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(SelectRoomViewController.submit))
    }

    func getList(build: String?, floor: String?){
        
        var resq = URLRequest(url: URL(string: "\(DOMAIN_NAME)/getRoom.php")!)
        resq.httpMethod = "POST"
        //building floor
        var state = 0
        
        if build != nil && floor != nil {
            state = 2
            resq.httpBody = "building=\(build!)&floor=\(floor!)".data(using: .utf8)
        }else if build != nil {
            state = 1
            resq.httpBody = "building=\(build!)".data(using: .utf8)
        }
        
        
        
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            if err == nil {
                if data != nil {
                    
                    let str = String(data: data!, encoding: .utf8)
                    if str != nil {
                        print(str!)
                        let compo = str!.components(separatedBy: "|")
                        
                        if compo.count > 0{
                            switch state {
                            case 0:
                                self.buildList = compo
                                
                                DispatchQueue.main.async {
                                    self.buildTableView.reloadData()
                                }
                                
                                break
                            case 1:
                                self.floorList = compo
                                
                                DispatchQueue.main.async {
                                    self.floorTableView.reloadData()
                                }
                                break
                            case 2:
                                self.roomList = compo
                                
                                DispatchQueue.main.async {
                                    self.roomTableView.reloadData()
                                }
                                break
                            default:
                                break
                            }
                        }
                        
                        
                        
                    }
                    
                }
            }
        }.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView.tag {
        case 1:
            if buildList != nil{
                return buildList!.count
            }
            break
        case 2:
            if floorList != nil{
                return floorList!.count
            }
            break
        case 3:
            if roomList != nil{
                return roomList!.count
            }
            break
        default:
            break
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        
        switch tableView.tag {
        case 1:
            if buildList != nil{
                let info = buildList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    cell.textLabel?.text = showName[1]
                }
            }
            break
        case 2:
            if floorList != nil{
                let info = floorList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    let floorName = showName[1].components(separatedBy: "-")
                    if floorName.count >= 2{
                        cell.textLabel?.text = floorName[1]
                    }else{
                        cell.textLabel?.text = floorName[0]
                    }
                }
            }
            break
        case 3:
            if roomList != nil{
                let info = roomList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    
                    let dormName = showName[1].components(separatedBy: "-")
                    if dormName.count >= 2{
                        cell.textLabel?.text = dormName[1]
                    }else{
                        cell.textLabel?.text = dormName[0]
                    }
                    
                    
                }
            }
            break
        default:
            break
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch tableView.tag {
        case 1:
            if buildList != nil{
                let info = buildList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    dormName = showName[1]
                    selectedBuildID = showName[0]
                    getList(build: selectedBuildID, floor: nil)
                    floorTableView.alpha = 1
                    roomTableView.alpha = 0
                }
            }
            break
        case 2:
            if floorList != nil{
                let info = floorList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    selectedFloorID = showName[0]
                    getList(build: selectedBuildID, floor: selectedFloorID)
                    roomTableView.alpha = 1
                }
            }
            break
        case 3:
            if roomList != nil{
                let info = roomList![indexPath.row] as! String
                let showName = info.components(separatedBy: ",")
                if showName.count >= 2{
                    selectedRoomID = showName[0]
                    let dormName = showName[1].components(separatedBy: "-")
                    
                    if dormName.count >= 2{
                        self.roomName = dormName[1]
                    }else{
                        self.roomName = dormName[0]
                    }
                    
                    submit()
                }
            }
            break
        default:
            break
        }
    }
    
    func submit(){
        if selectedBuildID != nil && selectedFloorID != nil && selectedRoomID != nil {
            UserDefaults.standard.set(selectedBuildID, forKey: "build")
            UserDefaults.standard.set(selectedFloorID, forKey: "floor")
            UserDefaults.standard.set(selectedRoomID, forKey: "room")
            UserDefaults.standard.set("\(dormName!)\(roomName!)", forKey: "name")
            _ = navigationController?.popViewController(animated: true)
            
            delegate?.didFinishSelectRoom(vc: self)
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
